package com.mdn.gcalendar.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.SequenceInputStream;
import java.io.Writer;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.mdn.gcalendar.service.JsonReaderService;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

@Service("jsonReaderService")
public class JsonReaderServiceImpl implements JsonReaderService {

	private static String templatePath = "json/%s";
	private static String macrosPath = "json/macros.fmtp";
	private static String defaultEncoding = "UTF-8";

	@Override
	public String getTemplateContent(String templateName, Map<String, String> data) {
		try {
			final String tmpl = String.format(templatePath, templateName);
			Configuration cfg = new Configuration();
			cfg.setDefaultEncoding(defaultEncoding);
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			FileInputStream fisTemplate = new FileInputStream(tmpl);
			FileInputStream fisMacros = new FileInputStream(macrosPath);
			SequenceInputStream sis = new SequenceInputStream(fisTemplate, fisMacros);
			Template template = new Template(tmpl, new InputStreamReader(sis, defaultEncoding), cfg, defaultEncoding);

			ByteArrayOutputStream toReturn = new ByteArrayOutputStream();
			Writer out = new OutputStreamWriter(toReturn, defaultEncoding);
			template.process(data, out);
			out.flush();
			fisTemplate.close();
			fisMacros.close();

			return toReturn.toString(defaultEncoding);
		} catch (Exception e) {
			return String.format("<error>%s</error>", e.getMessage());
		}
	}
}
